package com.kx.gateway.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * 这个类要处理
 * 1、获取nacos上的配置信息，且监听nacos上的配置信息。
 * 2、拿到配置信息之后，让网关应用的路由信息动态生效。
 *
 * @author Sun
 * @date 2021/8/4 17:30
 */
@Component
public class NacosDynamicRouteService implements ApplicationEventPublisherAware {

    /**
     * 应用动作发布者
     */
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * Nacos上的配置文件对应的dataId
     */
    private String dataId = "gateway-router";

    /**
     * Nacos上的配置文件对应的group
     */
    private String group = "DEFAULT_GROUP";

    /**
     * 获取nacos的服务器地址
     */
    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;


    /**
     * 路由信息的写入对象
     */
    @Resource
    private RouteDefinitionWriter routeDefinitionWriter;

    /**
     * 路由规则的保存对象
     */
    private static final List<String> ROUTE_LIST = new ArrayList<>();


    @PostConstruct
    public void dynamicRouteByNacosListener() {

        try {
            //获取nacos服务
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            //路由信息
            String config = configService.getConfig(dataId, group, 5000);

            //System.out.println("------获取config------"+config);
            //json解析路由信息
            List<RouteDefinition> routeDefinitions = JSONObject.parseArray(config, RouteDefinition.class);
            //逐一加入到路由信息中
            for (RouteDefinition routeDefinition : routeDefinitions) {
                addRoute(routeDefinition);
            }
            //把路由信息发布
            publish();

            configService.addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                /**
                 * 只要发生变化，这个方法就运行
                 * @param config 最新的文件内容
                 */
                @Override
                public void receiveConfigInfo(String config) {
                    //清空路由
                    clearRoute();
                    //json解析路由信息
                    List<RouteDefinition> routeDefinitions = JSONObject.parseArray(config, RouteDefinition.class);
                    //逐一加入到路由信息中
                    for (RouteDefinition routeDefinition : routeDefinitions) {
                        addRoute(routeDefinition);
                    }
                    //把路由信息发布
                    publish();
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清空路由信息的方法
     */
    private void clearRoute() {
        for (String id : ROUTE_LIST) {
            //逐个移除路由信息
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
        }
        ROUTE_LIST.clear();
    }

    /**
     * 添加路由信息的方法
     */
    private void addRoute(RouteDefinition definition) {
        routeDefinitionWriter.save(Mono.just(definition)).subscribe();
        ROUTE_LIST.add(definition.getId());
    }

    /**
     * 发布路由信息的方法
     */
    private void publish() {
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(routeDefinitionWriter));
    }

}
